package uk.gov.swmprobation.swm;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Sites<Main> extends ListActivity {

	String q="";
	ListAdapter adapter;
	NodeList nodes;
	public ArrayList<HashMap<String, String>> fullList = new ArrayList<HashMap<String, String>>();
	public ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    public ArrayList<HashMap<String, String>> filtered = new ArrayList<HashMap<String, String>>();
    private Filter filter;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_sites);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
		
		EditText search=(EditText)findViewById(R.id.etSearchbox);
		search.addTextChangedListener(new TextWatcher() {

		    @Override
		    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		        // TODO Auto-generated method stub
		    }

		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) {
		        // TODO Auto-generated method stub

		    }

		    @Override
		    public void afterTextChanged(Editable arg0) {
		    	((Filterable) adapter).getFilter().filter(arg0);
		    }
		});

		
		//Needed for the listItems
        InputStream is = getResources().openRawResource(R.raw.sites);
                
        Document doc = XMLfunctions.XMLfromFile(is);
        
		nodes = doc.getElementsByTagName("site");

		//fill in the list items from the XML document
		for (int i = 0; i < nodes.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();	

			Element e = (Element)nodes.item(i);
			map.put("title", XMLfunctions.getValue(e, "title"));
        	map.put("address", XMLfunctions.getValue(e, "address"));
        	map.put("phone", XMLfunctions.getValue(e, "phone"));
        	map.put("postcode", XMLfunctions.getValue(e, "postcode"));
        	fullList.add(map);
		}		
		
		class MyStringComparable implements Comparator<HashMap<String, String>>{

			@Override
			public int compare(HashMap<String, String> lhs,
					HashMap<String, String> rhs) {
				
				return lhs.get("title").compareTo(rhs.get("title"));
			}

		}
		
		Collections.sort(fullList, new MyStringComparable());
		
		mylist.clear();
        mylist.addAll(fullList);
		
		//Make a new listadapter
        adapter = new swmAdapter(this, mylist , R.layout.site_item,
                        new String[] { "title", "address", "phone" },
                        new int[] { R.id.item_title, R.id.item_address, R.id.item_phone });
        
        setListAdapter(adapter);
        
		//Get the listView ( from: ListActivity )
        final ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener(){
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		final HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
        		final CharSequence[] items = {"Call", "Map", "Cancel"};
        		AlertDialog.Builder listBuilder = new AlertDialog.Builder(new ContextThemeWrapper(Sites.this, R.style.ClickableView));
        		listBuilder.setItems(items, new DialogInterface.OnClickListener() {
        		   public void onClick(DialogInterface dialog, int item) {
        			   String url;
        			   Intent intent;
        			   switch(item) {
        			    case 0:
        			    	intent = new Intent(Intent.ACTION_DIAL);
        			    	String pn = "tel:" + o.get("phone");
        			    	intent.setData(Uri.parse(pn));
        			        startActivity(intent);
        			        break;
        			    case 1:
        			    	url ="http://maps.google.co.uk/?q=" +o.get("postcode")+ "&amp;z=14";
        			        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        			        startActivity(intent);
        			        break;
        			    default:        			      
        			}

        		   }
        		});
        		AlertDialog alertList = listBuilder.create();
        		alertList.show();
        		} 
        	});
        }
		
    public class swmAdapter extends SimpleAdapter
    {

    	public swmAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			// TODO Auto-generated constructor stub
		}

		@Override
        public Filter getFilter()
        {
            if(filter == null)
                filter = new SiteFilter();
            return filter;
        }

        private class SiteFilter extends Filter
        {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                // NOTE: this function is *always* called from a background thread, and
                // not the UI thread.
                constraint = constraint.toString().toLowerCase();
                FilterResults result = new FilterResults();
                if(constraint != null && constraint.toString().length() > 0)
                {
                	ArrayList<HashMap<String, String>> filt = new ArrayList<HashMap<String, String>>();
                	ArrayList<HashMap<String, String>> lItems = new ArrayList<HashMap<String, String>>();
                    synchronized (this)
                    {
                        lItems.addAll(fullList);
                    }
                    for(int i = 0, l = lItems.size(); i < l; i++)
                    {
                    	HashMap<String, String> m = lItems.get(i);
                    	String details = m.get("title")+m.get("address")+m.get("phone");
                        if(details.toLowerCase().contains(constraint))
                            filt.add(m);
                    }
                    result.count = filt.size();
                    result.values = filt;
                }
                else
                {
                    synchronized(this)
                    {
                        result.count = fullList.size();
                        result.values = fullList;
                    }
                }
                return result;
            }

            @SuppressWarnings("unchecked")
			@Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                // NOTE: this function is *always* called from the UI thread.
                filtered = (ArrayList<HashMap<String, String>>) results.values;
                notifyDataSetChanged();
                mylist.clear();
                mylist.addAll(filtered);
                notifyDataSetInvalidated();
            }

    	
    }
    }
	}





